package com.sunsharing.transport.file;

import com.sunsharing.common.Constant;
import com.sunsharing.common.URL;
import com.sunsharing.common.anno.Factory;
import com.sunsharing.common.config.ChannelModel;
import com.sunsharing.common.config.Config;
import com.sunsharing.common.config.NodeModel;
import com.sunsharing.common.utils.StringUtils;
import com.sunsharing.transport.ConnectClients;
import com.sunsharing.transport.IoHandle;
import com.sunsharing.transport.Server;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-4-30
 * Time: 下午3:38
 * To change this template use File | Settings | File Templates.
 */
@Factory(key="FILE")
public class FileServer implements Server {


    @Override
    public void startServer(URL url, IoHandle ioHandle) {
        url.putPar(Constant.URL_PAR_TO_NODE_ID,Config.getInstance().getNodeId());
        NodeModel nodeM = Config.getInstance().
                getNodeModelByNodeId(Config.getInstance().getNodeId());
        List<ChannelModel> channelModels = Config.getInstance().getMyChannelModel();
        for(ChannelModel model:channelModels)
        {
            if(model.type.equals(Constant.PROTOCOL_FILE))
            {
                String lisen = model.lisen;
                if(StringUtils.isBlank(lisen))
                {
                    throw new RuntimeException("File类型必须配置Listen模块");
                }
                String[] fromNodes = lisen.split(",");
                for(int i=0;i<fromNodes.length;i++)
                {
                    String fn = fromNodes[i];
                    URL u = URL.clone(url);
                    u.putPar(Constant.URL_PAR_FROM_NODE_ID,fn);
                    u.putPar(Constant.URL_PAR_ISCLIENT,"false");
                    u.putPar(Constant.URL_PAR_BYCLIENT,"false");
                    u.putPar(Constant.URL_PAR_ROOT_FILE_PATH,nodeM.rootpath);
                    FileChannel f = new FileChannel(u,ioHandle);
                    ConnectClients.addClient(f);
                }

            }
        }

    }

    @Override
    public void stopServer() {

    }
}
